<template>
  <div class="ConferenceRoomManagement">
    <div class="formPage">
      <div style="margin-top: 20px; margin-bottom: 20px">
        <el-form ref="querryForm" label-width="80px">
          <el-form-item label="校区">
            <el-select v-model="querryForm.campus" @change="fetch" :disabled="role===0">
              <el-option
                  :value="0"
                  label="全部校区"
                  style="text-align: center"
              ></el-option>
              <el-option
                  v-for="item in campusList"
                  :key="item.id"
                  :label="item.campusName"
                  :value="item.id"
                  style="text-align: center"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-button
            type="primary"
            @click="openMeetingRoomDialog"
            v-if="role ===1"
        >新建会议室
        </el-button>
      </div>

      <div>
        <el-table :data="tableData" stripe>
          <el-table-column label="校区" min-width="100">
            <template v-slot="scope">
              {{ getCampusName(scope.row.campus) }}
            </template>
          </el-table-column>
          <el-table-column prop="roomName" label="会议室" min-width="100">
          </el-table-column>
          <el-table-column prop="otherConfig" label="配置设施" min-width="400">
          </el-table-column>
          <el-table-column label="座位" min-width="60">
            <template v-slot="scope">
              <!-- 计算并显示主座人数和从座人数的总和 -->
              {{ computeTotalSeats(scope.row) }}
            </template>
          </el-table-column>

          <el-table-column label="使用状态" min-width="80">
            <template v-slot="scope">
              <el-tag
                  size="small"
                  effect="plain"
                  :type="scope.row.useStatus === 1 ? 'danger' : 'success'"
              >
                {{ scope.row.useStatus === 1 ? "使用中" : "未使用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="reservation" label="预约会议" min-width="80">
            <template v-slot="scope">
              <el-button
                  text
                  size="small"
                  class="fun-button"
                  @click="reserveConference(scope.row)"
              >预约
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
              prop="operation"
              label="操作"
              v-if="role === 1"
              min-width="140"
          >
            <template v-slot="scope">
              <el-button
                  text
                  size="small"
                  class="fun-button"
                  @click="openEditDialog(scope.row)"
              >修改
              </el-button>
              <el-button
                  text
                  size="small"
                  class="fun-button"
                  @click="confirmDelete(scope.row)"
                  style="color: red"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="Pagination">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10]"
            :page-size="querryForm.pageSize"
            :total="querryForm.total"
            :current-page="querryForm.pageNum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
      <conference-room-dialog
          :value="editDialogVisible"
          :roomData="editData"
          :mode="isEditMode"
          @save="handleSave"
          @dataUpdated="fetch"
      />
    </div>
  </div>
</template>

<script>
import ConferenceRoomDialog from '@/components/ConferenceRoomDialog.vue'
import {Paginationuery, DeleteRoom} from '@/api'

export default {
  name: 'ConferenceRoomManagement',
  components: {
    ConferenceRoomDialog: ConferenceRoomDialog,
  },

  data() {
    return {
      querryForm: {
        campus: this.$store.getters.getUserCampus, // 校区
        pageNum: 1,
        pageSize: 5,
        total: 0,
      },
      tableData: [],
      editDialogVisible: false,
      isEditMode: true,
      editData: {},
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    openMeetingRoomDialog() {
      this.editData = {} // 重置或为新建会议室设置默认值
      this.isEditMode = false // 设置为新建模式
      this.editDialogVisible = true
    },

    openEditDialog(row) {
      this.editData = JSON.parse(JSON.stringify(row))
      this.isEditMode = true
      this.editDialogVisible = true
    },
    confirmDelete(row) {
      this.$confirm('此操作将永久删除该会议室, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            this.deleteRoom(row.id)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
    },

    deleteRoom(roomId) {
      DeleteRoom(roomId)
          .then((response) => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetch() // 重新加载数据
            } else {
              this.$message.error('删除失败: ' + response.msg)
            }
          })
          .catch((error) => {
            this.$message.error('删除失败')
            console.error('删除失败:', error)
          })
    },
    computeTotalSeats(room) {
      if (room) {
        // 确保配置存在且座位数是有效的数字，否则视为0
        const mainSeats = room.mainSeats || 0
        const sideSeats = room.sideSeats || 0
        return mainSeats + sideSeats
      }
      return 0 // 如果没有配置信息，默认返回0
    },
    getCampusName(campusId) {
      const campus = this.campusList.find((item) => item.id === campusId)
      return campus ? campus.campusName : '未知校区'
    },
    handleSave(updatedData) {
      // 更新表格数据或调用 API
      const index = this.tableData.findIndex((d) => d.name === updatedData.name)
      if (index !== -1) {
        this.tableData[index] = {...updatedData}
      }
    },
    reserveConference(row) {
      this.$router.push({
        name: 'ConferenceReservations',
        query: {
          status: 'add',
          campus: row.campus,
          conferenceRoomId: row.id,
        },
      })
    },

    fetch() {
      Paginationuery(this.querryForm)
          .then((response) => {
            if (response && response.data) {
              this.tableData = response.data.rows
              this.querryForm.total = Number(response.data.total)
            } else {
              this.tableData = []
              console.error('Invalid data structure:', response)
            }
          })
          .catch((error) => {
            console.error('Failed to fetch data:', error)
            this.tableData = []
          })
    },
    handleSizeChange(newSize) {
      this.querryForm.pageSize = newSize
      this.fetch() // 当页面大小改变时重新加载数据
    },
    handleCurrentChange(newPage) {
      this.querryForm.pageNum = newPage
      this.fetch() // 当页码改变时重新加载数据
    },
  },

  computed: {
    role() {
      return this.$store.getters.getRole
    },
    campusList() {
      return this.$store.getters.getCampusList
    },

  },
}
</script>

<style lang="less" scoped>
@import '@/assets/style/ConferenceRoomManage.less';


</style>
